package com.cms.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.cms.ExcelView;
import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.entity.Order;
import com.cms.entity.Pack;
import com.cms.entity.PackProduct;
import com.cms.entity.Payment;
import com.cms.entity.Product;
import com.cms.routes.RouteMapping;
import com.cms.util.DBUtils;
import com.cms.util.SystemUtils;
import com.cms.util.export.ExcelOrder;
import com.cms.util.fegine.FegineApi;
import com.cms.util.fegine.FegineResponse;


/**
 * Controller - 订单
 * 
 * 
 * 
 */
@RouteMapping(url = "/admin/order")

public class OrderController extends BaseController{

	/**
	 * 查看
	 */
	public void view(){
		Long id = getParaToLong("id");
		Order order = new Order().dao().findById(id);
		setAttr("order", order);
		render(getView("order/view"));
	}
	
	public void addPack(){
		Long id = getParaToLong("id");
		Order order = new Order().dao().findById(id);
		setAttr("order", order);
		render(getView("order/pack"));
	}
	
	public void deletePack(){
		Long packId = getParaToLong("packId");
		new Pack().dao().deleteById(packId);
		new PackProduct().dao().deleteByPackId(packId);
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	
	//打包修改
	public void updatePackProduct(){
		Pack pack = getModel(Pack.class,"",true); 
		if(StringUtils.isNotBlank(pack.getPhoto())){
        	String photo = pack.getPhoto();
        	photo = photo.replace(SystemUtils.getConfig().getImgUrl(), "");
        	pack.setPhoto(photo);
        }
		pack.setCreateDate(new Date());
		pack.setModifyDate(new Date());
		pack.save();
		
		Long[] productIds = getParaValuesToLong("productId");
		Integer[] quantitys = getParaValuesToInt("quantity");
		if(ArrayUtils.isNotEmpty(productIds)){
			for(int i=0;i<productIds.length;i++){
				Long productId = productIds[i];
				Integer quantity = quantitys[i];
				Product product = new Product().dao().findById(productId);
				PackProduct packProduct = new PackProduct();
				packProduct.setCreateDate(new Date());
				packProduct.setModifyDate(new Date());
				packProduct.setImage(product.getImage());
				packProduct.setName(product.getName());
				packProduct.setPackId(pack.getId());
				packProduct.setProductId(productId);
				packProduct.setQuantity(quantity);
				packProduct.setSn(product.getSn());
				packProduct.save();
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	
	/**
	 * 发货
	 */
	public void shipping(){
		Long id = getParaToLong("id");
		Order order = new Order().dao().findById(id);
		order.setStatus(Order.Status.SHIPPED.ordinal());
		order.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 物流
	 */
	public void traffic(){
		Long packId = getParaToLong("packId");
		Pack pack = new Pack().dao().findById(packId); 
		FegineResponse response = FegineApi.getInfo(pack.getExpressNumber(), Pack.ExpressCode.expressCodeValueMap.get(pack.getExpressCode()).name());
		setAttr("infos", response.getResult().getList());
		render(getView("order/traffic"));
	}
	
	/**
	 * 完成
	 */
	public void complete(){
		Long id = getParaToLong("id");
		Order order = new Order().dao().findById(id);
		order.setStatus(Order.Status.COMPLETED.ordinal());
		order.update();
		redirect("/admin/order/view?id="+id);
	}
	
	
	/**
	 * 列表
	 */
	public void list(){
		Long memberId = getParaToLong("memberId");
	    String sn = getPara("sn");
	    String consignee = getPara("consignee");
	    Order.Status status = getParaToEnum(Order.Status.class,"status");
	    Integer pageNumber = getParaToInt("pageNumber");
        if(pageNumber==null){
            pageNumber = 1;
        }
		setAttr("page", new Order().dao().findPage(sn,consignee,status,memberId,null,pageNumber,PAGE_SIZE));
		setAttr("sn", sn);
		if(status!=null){
			setAttr("status", status.name());
		}
		render(getView("order/list"));
	}
	
	public void updateStatus(){
		Order.Status status = getParaToEnum(Order.Status.class,"status");
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		order.setStatus(status.ordinal());
		order.setModifyDate(new Date());
		order.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	
	public void export(){
		String sn = getPara("sn");
		Order.Status status = getParaToEnum(Order.Status.class,"status");
        String filterSql = " ";
        if(StringUtils.isNotBlank(sn)){
            filterSql+= " and sn like '%"+sn+"%'";
        }
        if(status!=null){
        	filterSql+=" and status="+status.ordinal();
        }
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        List<Order> orders = new Order().dao().find("select * from cms_order where 1=1 "+filterSql+orderBySql);
	    String filename = "订单_" + DateFormatUtils.format(new Date(), "yyyyMM") + ".xls";
	    String[] contents = new String[3];
	    contents[0] = "生成数量" + ": " + orders.size();
	    contents[1] = "操作员" + ": " + getCurrentAdmin().getUsername();
	    contents[2] = "生成日期" + ": " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	    List<ExcelOrder> data = new ArrayList<>();
	    for(Order order : orders){
	    	ExcelOrder excelOrder = new ExcelOrder();
	    	excelOrder.setId(order.getId()+"");
	    	excelOrder.setSn(order.getSn());
	    	excelOrder.setAmount(order.getAmount().toString());
	    	Member member = order.getMember();
	    	Long memberId = member.getId();
	    	String nickname = member.getNickname();
	    	if(StringUtils.isBlank(nickname)){
	    		nickname = "";
	    	}
	    	String mobile = member.getMobile();
	    	if(StringUtils.isBlank(mobile)){
	    		mobile = "";
	    	}
	    	excelOrder.setMember("ID:"+memberId+"\r\n昵称:"+nickname+"\r\n手机号码:"+mobile);
	    	String consignee = order.getConsignee();
	    	if(StringUtils.isBlank(consignee)){
	    		consignee = "";
	    	}
	    	String phone = order.getPhone();
	    	if(StringUtils.isBlank(phone)){
	    		phone = "";
	    	}
	    	String province = order.getProvince();
	    	if(StringUtils.isBlank(province)){
	    		province = "";
	    	}
	    	String city = order.getCity();
	    	if(StringUtils.isBlank(city)){
	    		city = "";
	    	}
	    	String district = order.getDistrict();
	    	if(StringUtils.isBlank(district)){
	    		district = "";
	    	}
	    	String address = order.getAddress();
	    	if(StringUtils.isBlank(address)){
	    		address = "";
	    	}
	    	excelOrder.setReceiver("收货人:"+consignee+"\r\n手机号码:"+phone+"\r\n地址:"+province+";"+city+";"+district+";"+address);
	    	String paymentMethodName = Payment.Method.methodValueMap.get(order.getPaymentMethod()).getText();
	    	excelOrder.setPaymentMethod(paymentMethodName);
	    	String shippingMethodName = "";
	    	excelOrder.setShippingMethod(shippingMethodName);
	    	excelOrder.setCreateDate(DateFormatUtils.format(order.getCreateDate(), "yyyy-MM-dd"));
	    	String statusName = Order.Status.statusValueMap.get(order.getStatus()).getText();
	    	excelOrder.setStatus(statusName);
	    	String memo = order.getMemo();
	    	if(StringUtils.isBlank(memo)){
	    		memo = "";
	    	}
	    	excelOrder.setMemo(memo);
	    	data.add(excelOrder);
	    }
	    try {
	        new ExcelView(filename, null, new String[] { "id","sn","amount","member","receiver","paymentMethod","shippingMethod","status","memo","createDate" }, new String[] { "ID","编号","金额","会员","收货人","支付方式","配送方式","状态","附言","创建日期"}, null, null, data, contents).buildExcelDocument(getRequest(), getResponse());
	        renderNull();
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	}
}
